package com.ruoyi.framework.interceptor;

import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.esotericsoftware.minlog.Log;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.helper.LoginHelper;
import jdk.nashorn.internal.ir.IfNode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <简述>
 * <详细描述>
 *
 * @author syf
 * @date 2024年07月25日 17:19
 */
@Slf4j
public class TestDynamicInterceptorDemo implements HandlerInterceptor {

    //请求处理之前调用
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1-根据请求判断
        String requestURI = request.getRequestURI();
        log.info("requestURI:{}", requestURI);
        String ds = "";
        if (requestURI.contains("/testDynamic7")){
            ds = "slave";
        }
        //2-根据请求头动态切换
        String datasource = request.getHeader("datasource");
        if (StringUtils.isNotBlank(datasource)){
            ds = datasource;
        }
        //3- 更具登录用户动态切换
        LoginUser loginUser = null;
        try {
            loginUser = LoginHelper.getLoginUser();
            log.info("loginUser:{}", loginUser);
            if("admin".equals(loginUser.getUsername())){
                ds = "master";
            }
        }catch (Exception e){

        }
        DynamicDataSourceContextHolder.push(ds);
        return true;
    }

    //请求处理但是页面未渲染调用
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
    }

    //请求处理完毕调用
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
    }
}
